package com.dawnClass.controller;

import com.dawnClass.pojo.Article;
import com.dawnClass.pojo.Consumer;
import com.dawnClass.service.ArticleService;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/community")
    public ModelAndView getArticle(String label){
        System.out.println(label);
        ModelAndView mav = new ModelAndView();
        //调用service对象
        ServiceResponse articleServiceResponse = articleService.getArticle(label);
        //绑定数据到ModelAndView,页面跳转
        mav.addObject("label",label);
        mav.addObject("articleServiceResponse",articleServiceResponse);
        mav.setViewName("article/community");
        return mav;
    }

    @GetMapping("/community/article/{articleId}")
    public ModelAndView getArticleById(@PathVariable("articleId") Integer articleId){

        ModelAndView mav = new ModelAndView();
        //调用service对象
        ServiceResponse articleDetails = articleService.getArticleDetails(articleId);
        byte[] articleContent = ((Article) articleDetails.getdata()).getArticleContent();
        //绑定数据到ModelAndView,页面跳转
        mav.addObject("articleContent",new String(articleContent));
        mav.addObject("articleDetails",articleDetails);
        mav.setViewName("article/article");
        return mav;
    }


    @GetMapping("/community/writeArticle")
    public ModelAndView toWriteArticle(){
        ModelAndView mav = new ModelAndView();
        //绑定数据到ModelAndView,页面跳转
        mav.setViewName("article/writeArticle");
        return mav;
    }


    @PostMapping("/community/saveArticle")
    public int saveArticle(String articleName , String articleContent , Date articleDatetime , HttpSession session){
        ServiceResponse serviceResponse = (ServiceResponse) session.getAttribute("ServiceResponse");
        Consumer loginConsumer = (Consumer) serviceResponse.getdata();

        //调用方法保存文章
        int row = articleService.saveArticle(articleName , articleContent , articleDatetime , loginConsumer.getConsumerId());
        return row;
    }

}
